package edu.pku.sei.pgie.persistence.dao;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import edu.pku.sei.pgie.analyzer.core.Context;
import edu.pku.sei.pgie.analyzer.core.ICollector;
import edu.pku.sei.pgie.analyzer.internal.Metrics;
import edu.pku.sei.pgie.beans.CodeEntity;
import edu.pku.sei.pgie.beans.Link;
import edu.pku.sei.pgie.beans.Structure;
import edu.pku.sei.pgie.persistence.PersistenceException;

public class DatabaseCollector implements ICollector{
    private static Log logger = LogFactory.getLog(DatabaseCollector.class);

    LinkDAO linkDao;
    StructureDAO structureDao;
    EntityDAO entityDao;

    public DatabaseCollector(Context context) throws PersistenceException{
        DataSource dataSource = DataSourceFactory.getDataSource();
        try {
        dataSource.getConnection();
        } catch(Exception e) {
            throw new PersistenceException("database configuration exception");
        }
        linkDao = new LinkDAO();
        structureDao = new StructureDAO();
        entityDao = new EntityDAO();
    }

    public void collect(Structure structure)  {
        if(structure != null) {
            try {
                structureDao.createPackage(structure);
            } catch (SQLException e) {
                logger.warn("structure dao exception",e);
            }
        }
    }

    public void collect(Link link) {
        if(link != null) {
            try {
                linkDao.createLink(link);
            } catch(Exception e) {
                logger.warn("link dao exception", e);
            }
        }
    }

    public void collect(CodeEntity codeEntity) {
        if(codeEntity != null) {
            try {
                entityDao.createEntity(codeEntity);
            } catch(Exception e) {
                logger.warn("code entity dao exception",e);
            }
        }
    }

    public void close() {

    }

    public void collect(Metrics metrics) {
        throw new RuntimeException();
    }

    public long nextCodeId() {
        throw new RuntimeException();
    }

    /* (non-Javadoc)
     * @see edu.pku.sei.pgie.analyzer.core.ICollector#nextStructureId()
     */
    public long nextStructureId() {
        // TODO Auto-generated method stub
        return 0;
    }

}
